package com.yunxi.order.exception;

import com.alibaba.csp.sentinel.adapter.spring.webmvc_v6x.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yunxi.common.result.CommonResult;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;

import java.io.PrintWriter;

/**
 * 自定义流控异常
 *
 * @author: lidy
 * @date: 2025-01-18 20:15
 */
@Component
public class MyBlockExceptionHandler implements BlockExceptionHandler {

    private final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public void handle(HttpServletRequest request,
                       HttpServletResponse response,
                       String resourceName, BlockException e) throws Exception {
        response.setContentType("application/json;charset=utf-8;");
        // 请求太多，返回429
        response.setStatus(429);

        PrintWriter writer = response.getWriter();

        CommonResult<?> result = CommonResult.error(500,
                resourceName + " 被 Sentinel 限制了，原因：" + e.getClass());

        writer.write(objectMapper.writeValueAsString(result));
        writer.flush();
        writer.close();
    }

}
